﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using MVCBootstrap.Web.Mvc.Interfaces;
using SendGridMail;
using SendGridMail.Transport;
using mvcForum.Core.Abstractions.Interfaces;
using System.Configuration;
using System.Net.Configuration;

namespace MvcForum.Hosting.Azure {

	public class SendGridMailService : IMailService {

		public void Send(MailAddress from, IList<MailAddress> to, IList<MailAddress> replyTo, String subject, String body) {
			throw new NotImplementedException("does not support reply to");
		}

		public void Send(MailAddress from, IList<MailAddress> to, String subject, String body) {
			SendGrid message = SendGrid.GetInstance();
			message.Text = body;
			message.Subject = subject;
			message.From = from;
			foreach (MailAddress m in to) {
				message.AddTo(m.Address);
			}

			SmtpSection mailSettings = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");

			NetworkCredential credentials = new NetworkCredential(mailSettings.Network.UserName, mailSettings.Network.Password);

			SMTP transportSMTP = SMTP.GetInstance(credentials);
			transportSMTP.Deliver(message);
		}

		public void Send(String from, String to, String subject, String body) {
			this.Send(new MailAddress(from), new MailAddress[] { new MailAddress(to) }.ToList(), subject, body);
		}

		public void Send(String to, String subject, String body) {
			SmtpSection mailSettings = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
			//MailSettingsSectionGroup mailSettings = (MailSettingsSectionGroup)ConfigurationManager.GetSection("system.net/mailSettings");
			this.Send(mailSettings.From, to, subject, body);
		}
	}
}
